import dayjs from 'dayjs';
import type { App, Plugin } from 'vue';
import txtImg from '@/assets/img/fileImg/fileText.png';
import wordImg from '@/assets/img/fileImg/fileWord.png';
import excelImg from '@/assets/img/fileImg/fileExcel.png';
import pptImg from '@/assets/img/fileImg/fileTime.png';
import pdfImg from '@/assets/img/fileImg/filePdf.png';
import jpgImg from '@/assets/img/fileImg/fileJpg.png';
import mdImg from '@/assets/img/fileImg/fileMd.png';
import csvImg from '@/assets/img/fileImg/fileCsv.png';
import audioFrequencyImg from '@/assets/img/fileImg/fileMp3.png';
import videoImg from '@/assets/img/fileImg/fileMp4.png';
import htmlImg from '@/assets/img/fileImg/fileHtml.png';
import cssImg from '@/assets/img/fileImg/fileCss.png';
import jsImg from '@/assets/img/fileImg/fileJs.png';
import zipImg from '@/assets/img/fileImg/fileZip.png';
import jsonImg from '@/assets/img/fileImg/fileJson.png';
import xmlImg from '@/assets/img/fileImg/fileXml.png';
import normalImg from '@/assets/img/fileImg/fileNormal.png';

/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    const copyInput = document.createElement('input'); //创建一个input框获取需要复制的文本内容
    copyInput.value = text;
    document.body.appendChild(copyInput);
    copyInput.select();
    document.execCommand('copy');
    copyInput.remove();
    resolve(true);
  });
};

/**
 * @description 判断字符串是否是base64
 * @param {string} str
 */
export const isBase64 = (str: string): boolean => {
  if (str === '' || str.trim() === '') {
    return false;
  }
  try {
    return btoa(atob(str)) == str;
  } catch (err) {
    return false;
  }
};
// 对象转JSON
export const toJSON = (obj) => {
  return JSON.stringify(obj, (key, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined';
      case typeof value === 'symbol':
        return value.toString();
      case typeof value === 'function':
        return value.toString();
      default:
        break;
    }
    return value;
  });
};

/***
 * @description 格式化日期
 * @param time
 */
export const formatDate = (time = +new Date()) => dayjs(time).format('YYYY-MM-DD HH:mm:ss');

/**
 *  @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
  return items
    .filter((item) => item[link] == id)
    .map((item) => ({
      ...item,
      slots: { title: 'name' },
      children: generateTree(items, item.departmentid)
    }));
};

/***
 * @description 原生加密明文
 * @param {string} plaintext
 */
const encryption = (plaintext: string) => (isBase64(plaintext) ? plaintext : window.btoa(window.encodeURIComponent(plaintext)));

/**
 * @description 原生解密
 * @param {string} ciphertext
 */
const decryption = (ciphertext: string) => (isBase64(ciphertext) ? window.decodeURIComponent(window.atob(ciphertext)) : ciphertext);

export const getBase64 = (img: Blob, callback: (base64Url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any;
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component as T & Plugin;
};

/**
 * @description 字节转换为B、KB、MB
 * @param {string} byte 字节
 */
export const changeByte = (大小: number, 保留小数: number = 2) => {
  大小 = Math.abs(大小);
  if (0 == +大小) return '0B';
  const c = 1024,
    e = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const f = Math.floor(Math.log(+大小) / Math.log(c));
  return parseFloat((+大小 / Math.pow(c, f)).toFixed(保留小数)) + e[f];
};

/**
 * @description 过滤table字段
 * @param {string} showConfig key-value配置
 */
export const filterTable = (tables, showConfig) => {
  for (let i = 0; i < tables.length; i++) {
    if (Reflect.has(showConfig, tables[i].key) && !showConfig[tables[i].key]) {
      tables.splice(i, 1);
      i--;
    }
  }
  return tables;
};

/**
 * 预览文件
 * @param url 预览地址
 */
export const reviewFile = (url) => {
  const a = document.createElement('a');
  a.href = url;
  a.target = '_blank';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};
/**
 * 文件图标展示
 * @param suffix 文件格式后缀
 */
export const checkFileIcon = (suffix) => {
  const fileTypes = {
    // 文本文件
    doc: wordImg,
    docx: wordImg,
    txt: txtImg,
    md: mdImg,
    csv: csvImg,
    // 图像文件
    jpg: jpgImg,
    jpeg: jpgImg,
    png: jpgImg,
    gif: jpgImg,
    bmp: jpgImg,
    // 演示和幻灯片文件
    pptx: pptImg,
    ppt: pptImg,
    pdf: pdfImg,
    // 音频和视频文件
    mp3: audioFrequencyImg,
    wav: audioFrequencyImg,
    flac: audioFrequencyImg,
    avi: videoImg,
    mov: videoImg,
    mp4: videoImg,
    // 网页相关文件
    html: htmlImg,
    css: cssImg,
    js: jsImg,
    // 压缩文件
    zip: zipImg,
    rar: zipImg,
    // 其他文件形式
    xls: excelImg,
    xlsx: excelImg,
    json: jsonImg,
    xml: xmlImg
  };
  if (fileTypes[suffix]) {
    return fileTypes[suffix];
  } else {
    return normalImg;
  }
};
